package com.shijie99.russ.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shijie99.russ.Utils.Constant;
import com.shijie99.russ.pojo.User;
import com.shijie99.russ.service.IUserService;

@Controller
public class LoginController {
	private static final String LOGIN_PAGE = "login";
	private static final String INDEX_PAGE = "index";
	private static Logger logger = Logger.getLogger(LoginController.class);
	
	@Autowired
	private IUserService userservice;
	
	
	@RequestMapping(value={"/", "/index", "index.html", "index.html", "index.jsp","login"},method = RequestMethod.GET)
	public String index(HttpServletRequest request,HttpServletResponse response){
		User user = (User)request.getSession().getAttribute(Constant.SESSION_USER);
		if(user == null ){
			return LOGIN_PAGE;
		}
		return INDEX_PAGE;
		
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/login.ajax",method = RequestMethod.POST)
	public Object loign(String username,String password,String rememberme,HttpServletRequest request,HttpServletResponse response){
		User user = userservice.queryByName(username);
		JSONObject rjson = new JSONObject();
		if(user != null){
			if(password.equals(user.getPassword())){
				request.getSession().setAttribute(Constant.SESSION_USER, user);
				logger.info(username+"登录成功！");
				logger.info(JSON.toJSON(user));
				rjson.put("permission", "1");
				return JSON.toJSONString(rjson);
			}else{
				rjson.put("permission", "0");
				return JSON.toJSONString(rjson);
		 } 
		}
		rjson.put("permission", "0");
		return JSON.toJSONString(rjson);
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		//撤销session
		request.getSession().removeAttribute(Constant.SESSION_USER);
		
		return "redirect:/login";
	}

	
	
	

}
